import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Image, View } from '@tarojs/components';
// import Taro, { useDidShow } from '@tarojs/taro';
import Taro, { useRouter } from '@tarojs/taro';
import CardContainer from '../../components/cardContainer';
import VerticalSeparation from '../../components/VerticalSeparation';
import PageContainer from '../../components/pageContainer';
import PopupLayer from '../../components/popupLayer';
import Progress from '../../components/progress';
// import InputNumber from '../../components/inputNumber';
import Button from '../../components/button';
import Banner from './components/banner';
// import addPng from '../../assets/add.png';
import likePng from '../../assets/like.png';
import callPng from '../../assets/call.png';
import defaultHeaderPng from '../../assets/default_header.png';
import request from '../../common/request';
import PagefooterButton from '../../components/pagefooterButton';
import { formatTimeDate, getImagePath,formatTimeMoth } from '../../utils';
import './index.scss';

const seasonList = ['一季度', '二季度', '三季度', '四季度'];
const  preservationList = ['冷藏', '常温', '冷冻'];
const  packageList = ['箱装', '框装', '盒装', '散装'];
const  certificationList= ['有机', '绿色', '地理标志', 'GAP', 'HACCP'];
function Index() {
  const ref = useRef(null);
  const [ item, setItem] = useState({});
  const [ orderProduct, setOrderProduct] = useState({});
  const [ consignorUser, setConsignorUser] = useState({});
  const [ consignorOrderProduct, setConsignorOrderProduct] = useState({});
  const { certifiedStatus=2 } = Taro.getStorageSync('user') || {};
  const router = useRouter();
  const postData = useCallback(()=>{
    request({method : 'GET', tartget: 'orderConsignorOrderQuery', data: {condition: {id: router.params.id}} }).then((data)=>{
      if (data.success) {
        setItem(data.model);
        setOrderProduct(data.model.orderProduct || {});
        setConsignorUser(data.model.consignorUser || {});
      }
    });
    request({method : 'GET', tartget: 'consignorOrderProductQuery', data: {condition: {id: router.params.id}} }).then((data)=>{
      if (data.success) {
        setConsignorOrderProduct(data.model);
        // fdfd
      }
    });
  },[]);

  useEffect(()=>{
    postData();
  },[]);

  const phoneCall = useCallback(() =>{
    Taro.makePhoneCall({
      phoneNumber: consignorUser.phoneNumber,
      success: function() {
        console.log("拨打电话成功！");
      },
      fail: function() {
        console.log("拨打电话失败！");
      }
    })
  },[consignorUser.phoneNumber]);

  const onSubmit = useCallback(()=>{
    Taro.redirectTo({
      url: `/pages/consignmentOrder/index?consignorOrderId=${router.params.id}`,
    });
  },[]);

  const deadline = (item.deadline - new Date().getTime())<0 || item.saleQuantity >= item.totalQuantity;// 时间截止
  return (
    <PageContainer noPadding>
      <Banner item={item} />
      <CardContainer>
        <View className='product'>
          <View className='product-row1'>
            <View className='product-row1-text2'>{orderProduct.productName}</View>
          </View>
          <View className='product-row2'>
            <View className='product-row2-text'>
              {`${orderProduct.originRegion} ${orderProduct.originCity} ${orderProduct.originArea}`}
            </View>
            <View className='product-row2-text'>预计{formatTimeDate(item.expectArriveTime)}到货</View>
          </View>
          <View className='product-row3'>
            <View className='product-row3-progress'><Progress percentage={item.saleQuantity/item.totalQuantity} /></View>
            <View className='product-row2-text'>{item.saleQuantity}/{item.totalQuantity}件</View>
          </View>
        </View>
      </CardContainer>
      <VerticalSeparation />
      <VerticalSeparation />
      <CardContainer>
        <View className='message'>
          <Image
            className='message-img1'
            src={consignorUser.avatar || defaultHeaderPng}
            onClick={()=>{
              Taro.previewImage({
                current: consignorUser.avatar || defaultHeaderPng,
                urls: [consignorUser.avatar || defaultHeaderPng] ,
              });
            }}
          />
          <View className='message-text'>
            <View className='message-text1'>{consignorUser.subjectName}</View>
            <View className='message-text2'>
              {`${consignorUser.subjectRegion} ${consignorUser.subjectCity} ${consignorUser.subjectArea}`}
            </View>
          </View>
          {/* <Image
            className='message-img2'
            src={likePng}
          />
          <Image
            onClick={phoneCall}
            className='message-img2'
            src={callPng}
          /> */}
        </View>
      </CardContainer>
      <VerticalSeparation />
      <CardContainer>
        <View className='card'>
          <View className='title'>
            基本信息
          </View>
          <VerticalSeparation />
          <View className='row'>
            <View className='row-text1'>
              货品名称
            </View>
            <View className='row-text2'>
              {orderProduct.productName}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              货品品种
            </View>
            <View className='row-text2'>
              {orderProduct.categoryName}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              货源产地
            </View>
            <View className='row-text2'>
              {`${orderProduct.originRegion || ''} ${orderProduct.originCity || ''} ${orderProduct.originArea || ''}`.trim() || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              货源产季
            </View>
            <View className='row-text2'>
              {seasonList[orderProduct.season] || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              采摘时间
            </View>
            <View className='row-text2'>
              {formatTimeMoth(orderProduct.pickTime)  || '--'}
            </View>
          </View>
        </View>
      </CardContainer>
      <VerticalSeparation />
      <CardContainer>
        <View className='card'>
          <View className='title'>
            品种规格
          </View>
          <VerticalSeparation />
          {
           orderProduct?.specList?.map((i)=>{
              return (
                <View className='row'>
                  <View className='row-text1'>
                    {i.specName}
                  </View>
                  <View className='row-text2'>
                    {i.spec || ''}
                  </View>
                </View>
              );
            })
          }
        </View>
      </CardContainer>
      <VerticalSeparation />
      <CardContainer>
        <View className='card'>
          <View className='title'>
            供应信息
          </View>
          <VerticalSeparation />
          <View className='row'>
            <View className='row-text1'>
              保质期
            </View>
            <View className='row-text2'>
              {formatTimeDate(orderProduct.qualityAssuranceTime) || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              货架期
            </View>
            <View className='row-text2'>
              {formatTimeDate(orderProduct.shelfLife) || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              保存方式
            </View>
            <View className='row-text2'>
              {preservationList[orderProduct.preservationType] || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              包装方式
            </View>
            <View className='row-text2'>
              {packageList[orderProduct.packageType] || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              质量认证
            </View>
            <View className='row-text2'>
              {certificationList[orderProduct.certificationType] || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              合格证
            </View>
            <View className='row-text2'>
              {orderProduct.isHaveCertificate ? '有':'无'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              货品描述
            </View>
            <View className='row-text2'>
              {orderProduct.description || '--'}
            </View>
          </View>
        </View>
      </CardContainer>
      <VerticalSeparation />
      <CardContainer>
        <View className='card'>
          <View className='title'>
            更多代卖信息
          </View>
          <VerticalSeparation />
          <View className='row'>
            <View className='row-text1'>
              目的城市
            </View>
            <View className='row-text2'>
              {`${item?.market?.marketRegion || ''} ${item?.market?.marketCity || ''} ${item?.market?.marketArea || ''}`.trim() || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              目的市场
            </View>
            <View className='row-text2'>
              {item?.market?.marketName || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              预计发货时间
            </View>
            <View className='row-text2'>
              {formatTimeDate(item.expectDeliveryTime) || '--'}
            </View>
          </View>
          <View className='row'>
            <View className='row-text1'>
              预计到货时间
            </View>
            <View className='row-text2'>
              {formatTimeDate(item.expectArriveTime) || '--'}
            </View>
          </View>
        </View>
      </CardContainer>
      <VerticalSeparation height={58} />
      <VerticalSeparation height={58} />
      {
        certifiedStatus === 3 ? (
          <PagefooterButton
            oneButton={{
              text:'我要代卖',
              disabled: true,
              onClick:()=>{
                // 去认证
                Taro.navigateTo({
                  url: '/pages/login/index',
                });
              },
            }}
          />
        ):(
          <PagefooterButton
            oneButton={{
              text:deadline ? '预订已截止':'我要代卖',
              disabled: deadline,
              // addonBefore:(
              //   <View className='footerExtraButton' onClick={phoneCall}>
              //     <Image
              //       className='footerExtraButton-img'
              //       src={callPng}
              //     />
              //     <View>联系ta</View>
              //   </View>
              // ),
              onClick:()=>{
                if (!deadline) {
                  ref.current.show() // 弹出
                }
              },
            }}
          />
        )
      }
      <PopupLayer
        id='popupRef'
        direction='top'
        ref={ref}
      >
        <view className='modalBox'>
          <View className='modalBox-message'>
            {
              consignorOrderProduct.productCoverId && (
                <Image
                  className='modalBox-message-img'
                  src={getImagePath(consignorOrderProduct.productCoverId,consignorOrderProduct.productCoverCode)}
                />
              )
            }
            <View className='modalBox-message-left'>
              <View className='text1'>{consignorOrderProduct.productName}</View>
              <View className='text2'>
                {`${consignorOrderProduct?.orderProduct?.originRegion} ${consignorOrderProduct?.orderProduct?.originCity} ${consignorOrderProduct?.orderProduct?.originArea}`}
              </View>
            </View>
          </View>
          <View className='modalBox-guiGe'>
            <View className='modalBox-guiGe-title'>
              <View className='text1'>规格</View>
              <View className='extra' />
              <View className='text2'>单件重量</View>
              <View className='text3'>指导价</View>
            </View>
            {
              consignorOrderProduct?.orderSpecList?.map((i)=>{
                return (
                  <View className='modalBox-guiGe-row'>
                    <View className='text1'>{i.productSpecName}</View>
                    <View className='extra'>剩{i.remainingQuantity}件</View>
                    <View className='text2'>
                      {/*<View style={{ width: '70%'}}>
                        <InputNumber disabled value={i.unitWeight} />
                      </View>*/}
                      {i.unitWeight} 斤
                    </View>
                    <View className='text3'>
                      {/*<View style={{ width: '60%'}}>*/}
                      {/*  <InputNumber disabled value={i.unitPrice} />*/}
                      {/*</View>*/}
                      {i.unitPrice} 元/件
                    </View>
                  </View>
                );
              })
            }
          </View>
          <Button onClick={onSubmit}>确认</Button>
          <VerticalSeparation />
        </view>
      </PopupLayer>
    </PageContainer>
  );
}

export default Index;
